package com.pateo.bjev.contacts.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.SectionIndexer;
import android.widget.TextView;

import com.pateo.bjev.contacts.R;
import com.pateo.bjev.contacts.adapter.ContactAdapter;
import com.pateo.bjev.contacts.utils.Log;

/**
 * Created by pateo on 17-5-10.
 */

public class ContactSideBar extends View {
    private SectionIndexer sectionIndexer;
    private char[] letters = new char[]{'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
    private Paint paint;                    //画笔用来绘制字母
    private RecyclerView listView;
    private int focusedIndex = -1;          //点击选中的索引
    private int drawWidth, drawHeight;      //绘制单个字母的宽高

    public interface OnTouchChangedListener {
        void onTouchDown(char c);

        void onTouchUp();
    }

    private OnTouchChangedListener listener;

    public void setOnTouchChangedListener(OnTouchChangedListener listener) {
        this.listener = listener;
    }

    public void setListView(RecyclerView listView) {
        this.listView = listView;
        updateLetters();
        sectionIndexer = (SectionIndexer) listView.getAdapter();
    }

    public void updateLetters() {
        if (listView != null) {
            RecyclerView.Adapter adapter = listView.getAdapter();
            if (adapter instanceof ContactAdapter) {
                char[] les = ((ContactAdapter) adapter).getLetters();
                if (les != null && les.length > 0) {
                    letters = les;
                }
                postInvalidate();
            }
        }
    }

    public ContactSideBar(Context context) {
        super(context);
        init();
    }

    public ContactSideBar(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public ContactSideBar(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    private void init() {
        //设置画笔属性
        paint = new Paint();
        paint.setColor(Color.GRAY);
        paint.setTextSize(18f);
        paint.setTextAlign(Paint.Align.CENTER);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        drawWidth = getMeasuredWidth() / 2;           //宽度为sideBar的一半
        drawHeight = getMeasuredHeight() / letters.length;    //设置高度
    }

    @Override
    protected void onDraw(Canvas canvas) {
        for (int i = 0; i < letters.length; i++) {
            canvas.drawText(String.valueOf(letters[i]), drawWidth, drawHeight + (i * drawHeight), paint);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int pointerY = (int) event.getY();
        int selectedIndex = pointerY / drawHeight;
        if (selectedIndex >= letters.length) {
            selectedIndex = letters.length - 1;
        } else if (selectedIndex < 0) {
            selectedIndex = 0;
        }

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                //点击时设置为半透明
                setBackgroundColor(Color.parseColor("#33000000"));
            case MotionEvent.ACTION_MOVE:
                if (sectionIndexer == null) {
                    sectionIndexer = (SectionIndexer) listView.getAdapter();
                }
                //                Log.d(TAG, letters[selectedIndex] + "");
                //根据数组中的元素获取对应的组位置
                int position = sectionIndexer.getPositionForSection(letters[selectedIndex]);
                showLetterView(letters[selectedIndex]);
//                Log.d(ContactSideBar.class, "position:" + position+",selectedIndex="+selectedIndex);
                if (position == -1) {
                    return true;
                }
                if (selectedIndex != 0) {
                    if(selectedIndex == letters.length-1){
                        //最后一个要滑多一点
                        position += 5;
                    }
                    if (position != 0) {
                        //改变当前listView所处位置
                        listView.scrollToPosition(position);
                    }
                } else {
                    listView.scrollToPosition(position);
                }

                //重绘SideBar
                invalidate();
                if (null != listener) {
                    listener.onTouchDown(letters[selectedIndex]);
                }
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                //松开手指取消背景色
                setBackgroundResource(android.R.color.transparent);
                invalidate();
                if (null != listener) {
                    listener.onTouchUp();
                }
                break;
        }
        return true;
    }

    TextView show = null;
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            show.setVisibility(View.GONE);
        }
    };
    private void addLetterView(){
        WindowManager manager = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
        show = (TextView) LayoutInflater.from(getContext()).inflate(R.layout.letter_float_layout,null);

        WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
        layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL| WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        layoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_PANEL;
        layoutParams.format = PixelFormat.TRANSPARENT;
        layoutParams.gravity = Gravity.CENTER;
        layoutParams.width = 100;
        layoutParams.height = 100;

        manager.addView(show,layoutParams);
    }

    private void showLetterView(char letter){
        if(show==null){
            addLetterView();
        }
        if(handler.hasMessages(1001)){
            handler.removeMessages(1001);
        }
        show.setText(letter+"");
        if(show.getVisibility() != View.VISIBLE){
            show.setVisibility(View.VISIBLE);
        }
        handler.sendEmptyMessageDelayed(1001,3000);
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        try{
            WindowManager manager = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
            if(show!=null){
                manager.removeView(show);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
